<?php
namespace Core\Common\Model;

use Core\Common\Component\Cache\Cache;
use Core\Common\Helper\CacheLoader;
use Illuminate\Database\Query\Builder;

/**
 * Model的缓存能力
 * Trait ModelCachable
 * @package App\Model\Base
 * @method static CachedBuilder query()
 * @method static CachedBuilder remember($ttl = null, $key = null)
 */
trait ModelCachable
{
    /**
     * @var string 缓存使用的实例
     */
    protected $cacheDriver = 'default';

    /**
     * @var null|string 缓存前缀，不指定时使用默认
     */
    protected $cachePrefix = null;

    /**
     * 替换Model的QueryBuilder，使其附带缓存能力
     * @param Builder $query
     * @return CachedBuilder
     */
    public function newEloquentBuilder($query)
    {
        $cacheTtl = property_exists($this, 'cacheTtl') ? $this->cacheTtl : CachedBuilder::DEFAULT_TTL;

        $options = [
            'prefix' => $this->cachePrefix ?: $this->defaultCachePrefix(),
            'ttl' => $cacheTtl
        ];
        $cacheLoader = new CacheLoader(Cache::store($this->cacheDriver), $options);

        return new CachedBuilder($query, $cacheLoader);
    }

    /**
     * 默认缓存前缀
     * @return string
     */
    protected function defaultCachePrefix()
    {
        $className = get_called_class();
        if (strpos($className, "App\\Model\\") === 0) {
            $className = substr($className, 10);
        }
        return strtolower(str_replace('\\', ':', $className)) . ':';
    }
}